package com.yisu.expressway.manager.website.controller;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import com.yisu.expressway.manager.core.service.IEditorActionService;
import com.yisu.expressway.manager.domain.response.UploadImageResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by xlt on 2017/4/24.
 */
@Controller
@RequestMapping(value = "/editorAction")
public class EditorActionController {
    @Resource
    private IEditorActionService iEditorActionService;
    @RequestMapping(value = "/editorConfig.json", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String uEditorConfig(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            return new ActionEnter(request, rootPath).exec();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/uploadImage.json", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String uploadImage(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
        // String path="http://oeb6w1s1c.bkt.clouddn.com/161125095212641927949861.jpg";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("upfile");
        UploadImageResult uploadImageResult = iEditorActionService.UploadImage(file);
        JSONObject result = new JSONObject();
        result.put("state", "SUCCESS");
        result.put("url", uploadImageResult.getUrl());
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().write(result.toString());
        return null;
    }
}
